import {Component, EventEmitter, Input, OnChanges, OnDestroy, OnInit, Output, SimpleChanges} from '@angular/core';
import {FarmCoordinateComponent} from './farm-coordinate/farm-coordinate.component';
import {LimitedFarm} from '../limited-farm';
import {Router} from '@angular/router';
import {MatDialog, MatDialogConfig} from '@angular/material';
import {ApplicationService} from '../../../../service/application.service';
import {Farm} from '../../../../entity/farm.model';

@Component({
  selector: 'app-map',
  templateUrl: './map.component.html',
  styleUrls: ['./map.component.css'],
})
export class MapComponent implements OnInit, OnDestroy, OnChanges {


  /**
   * 风场选中项变化输出属性
   *
   * @memberof MapComponent
   */
  @Output() changeFarm = new EventEmitter<LimitedFarm>();

  /**
   * 风场集合输入属性
   *
   * @memberof MapComponent
   */
  @Input()
  farms: LimitedFarm[];

  /**
   * 当前风场实体
   *
   * @type {Farm}@memberof MapComponent
   */
  currentFarm: LimitedFarm;

  /**
   * 拖拽的风场实体
   *
   * @type {Farm}@memberof MapComponent
   */
  dragFarm: LimitedFarm;

  /**
   * 当前风场轮询下标
   *
   * @type {number}@memberof MapComponent
   */
  active: number;//当前风场下标

  /**
   * 定时器
   *
   * @type {*}@memberof MapComponent
   */
  timer: any;

  /**
   * 是否显示集控中心大楼图标
   *
   * @type {*}@memberof MapComponent
   */
  isShowImg: boolean = false;

  /**
   * 风场轮询时间间隔（单位（s））
   *
   * @memberof MapComponent
   */
  @Input()
  interval?: number = 10;

  /**
   * 是否有拖动权限
   *
   * @type {string[]}
   * @memberof MapComponent
   */
  isDrap: boolean;

  /**
   * Creates an instance of MapComponent.
   * @memberof MapComponent
   */
  /**
   * 风场缩放值范围1-0
   *
   * @memberof MapComponent
   */
  zoom = 1;
  mCenterX = 0;
  mCenterY = 0;

  constructor(
    private router: Router,
    private dialog: MatDialog,
    private application: ApplicationService,
  ) {

  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes['farms'] != null && changes['farms'].currentValue != null) {
      clearInterval(this.timer);
      setTimeout(() => {
        this.polling(this.active);
      }, this.interval * 1000);
    }
  }

  ngOnInit() {
    this.change();
    let subject = this.application.currentMenuParamsSubject.subscribe(
      next => {
        this.change();
      }
    );

    this.polling();

  }

  change() {
    if (this.application.currentMenuParams && this.application.currentMenuParams['FarmPositionUser']) {
      let paramValue = this.application.currentMenuParams.FarmPositionUser.paramValue.split(';'),
        userName = this.application.currentUser.userName,
        i = paramValue.findIndex(o => o == userName);
      if (i > -1) {
        this.isDrap = true;
      }
    } else {
      this.isDrap = false;
    }
    if (this.application.currentApplicationParams && this.application.currentApplicationParams['farmZoom']) {
      const num = Number(this.application.currentApplicationParams['farmZoom'].paramValue);
      this.zoom = (num > 1 || num < 0) ? 1 : num;
    }
    if (this.application.currentApplicationParams && this.application.currentApplicationParams['isShowMCenter']) {
      const num = Number(this.application.currentApplicationParams['isShowMCenter'].paramValue);
      this.isShowImg = num === 1 ? true : false;
    }
    if (this.application.currentApplicationParams && this.application.currentApplicationParams['mCenterPos']) {
      const mCenterPos = this.application.currentApplicationParams['mCenterPos'].paramValue;
      const arr = mCenterPos.split(';');
      this.mCenterX = Number(arr[0]);
      this.mCenterY = Number(arr[1]);
    }
  }


  /**
   * 组件卸载需要清空资源
   *
   * @memberof MapComponent
   */
  ngOnDestroy(): void {
    if (this.timer != null) {
      clearInterval(this.timer);
    }
  }

  /**
   * 选中风场
   *
   * @param {number} i
   * @param {Farm} item
   * @memberof MapComponent
   */
  onClick(i: number, item: LimitedFarm) {
    this.active = i;
    this.currentFarm = item;
    this.changeFarm.emit(this.currentFarm);
    clearInterval(this.timer);
    setTimeout(() => {
      this.polling(this.active);
    }, this.interval * 1000);
  }

  /**
   * 风场轮询
   *
   * @memberof MapComponent
   */
  polling(active: number = 0) {
    this.active = active;
    if (this.farms != null && this.farms.length > 0) {

      clearInterval(this.timer);
      this.timer = setInterval(() => {
        if (this.active < this.farms.length - 1) {
          this.active++;
        } else {
          this.active = 0;
        }
        this.currentFarm = this.farms[this.active];
        this.changeFarm.emit(this.currentFarm);
      }, this.interval * 1000);
    }
  }

  ondblclick(farm: Farm) {
    if (this.currentFarm.farmCategory == 'winfarm') {
      this.router.navigate(['/monitor/turblist', farm.farmId]);
    } else {
      this.router.navigate(['/monitor/inverterlist', farm.farmId]);
    }
  }

  onDragStart(event: DragEvent, farm: LimitedFarm) {
    if (!this.isDrap) return false;
    this.dragFarm = farm;
  }

  onDrop(event: DragEvent) {
    if (!this.isDrap) return false;
    let target = (event as any).path[0];
    if (target.className == 'map') {

      let clientHeight = target.clientHeight;
      let clientWidth = target.clientWidth;
      let offsetX = event.offsetX - 83 / 2;
      let offsetY = event.offsetY - 113 / 2;

      let newPosx = Number.parseFloat((offsetX / clientWidth * 100).toFixed(2));
      let newPosy = Number.parseFloat((offsetY / clientHeight * 100).toFixed(2));

      let oldPosx = this.dragFarm.posx;
      let oldPosy = this.dragFarm.posy;

      this.dragFarm.posx = newPosx;
      this.dragFarm.posy = newPosy;

      let config = new MatDialogConfig();
      config.position = {top: `${event.clientY}px`, left: `${event.clientX + 24}px`}
      config.data = {
        farm: this.dragFarm,
        new: {posx: newPosx, posy: newPosy},
        old: {posx: oldPosx, posy: oldPosy}
      };
      this.dialog.open(FarmCoordinateComponent, config);
    }
  }

  onDragEnd(event: DragEvent) {
    if (!this.isDrap) return false;
    this.dragFarm = null;
  }
}
